#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>

// 根据实际硬件设置期望值（单位：MB）
#define DDR_EXPECTED_MB 3807   // 3898228 kB ≈ 3807 MB
#define DDR_TOLERANCE_MB 64    // ±64MB 容差

void ensure_userfs_dir() {
    struct stat st = {0};
    if (stat("/userfs", &st) == -1) {
        mkdir("/userfs", 0755);
    }
}

int get_memtotal_mb() {
    FILE *fp = fopen("/proc/meminfo", "r");
    if (!fp) return -1;

    char line[128];
    while (fgets(line, sizeof(line), fp)) {
        if (strncmp(line, "MemTotal:", 9) == 0) {
            long kb;
            if (sscanf(line + 9, "%ld", &kb) == 1) {
                fclose(fp);
                return (int)(kb / 1024); // 转为 MB
            }
        }
    }
    fclose(fp);
    return -1;
}

int ddr_test() {
    printf("=======  DDR test starting   ========\n");

    int mem_mb = get_memtotal_mb();
    if (mem_mb <= 0) {
        printf("Failed to read MemTotal from /proc/meminfo\n");
        return -1;
    }

    printf("Detected MemTotal: %d MB\n", mem_mb);

    if (mem_mb >= (DDR_EXPECTED_MB - DDR_TOLERANCE_MB) &&
        mem_mb <= (DDR_EXPECTED_MB + DDR_TOLERANCE_MB)) {
        printf("DDR test successful\n");
        return 0;
    } else {
        printf("DDR test failed: expected %d±%d MB, got %d MB\n",
               DDR_EXPECTED_MB, DDR_TOLERANCE_MB, mem_mb);
        return -1;
    }
}

int main() {
    ensure_userfs_dir();

    if (ddr_test() == 0) {
        printf("DDR 测试成功\n");
        system("echo \"$(date)：DDR 测试成功\" >> /userfs/all.txt");
    } else {
        printf("DDR 测试失败\n");
        system("echo \"$(date)：DDR 测试失败\" >> /userfs/all.txt");
    }

    return 0;
}